import java.util.concurrent.BlockingQueue;

class MyBolckingQueue{
    private int[] data=new int[1000];
    private int size=0;
    private int head=0;
    private int tail=0;

    //锁对象
    private Object locker=new Object();

    public void put(int value) throws InterruptedException {
        synchronized (locker){
            if(size==data.length){
                locker.wait();
            }
            data[tail]=value;
            tail++;
            if(tail>=data.length){
                tail=0;
            }
            size++;
            locker.notify();
        }
    }
    public Integer take() throws InterruptedException {
        synchronized (locker){
            if(size==0){
                locker.wait();
            }
            int ret=data[head];
            head++;
            if(head>=data.length){
                head=0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }
}
public class Demo22 {
    private static MyBolckingQueue queue=new MyBolckingQueue();
    public static void main(String[] args) {
        //实现一个生产者消费者模型
        Thread producer=new Thread(()->{
            int num=0;
            while(true){
                try {
                    System.out.println("生产了:"+num);
                    queue.put(num);
                    num++;
                    //当生产者生产的慢的时候，消费者也会跟着慢
                    //Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();

        Thread customet=new Thread(()->{
            while(true){
                try {
                    int num = queue.take();
                    System.out.println("消费了:"+num);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customet.start();



        /*MyBolckingQueue queue=new MyBolckingQueue();
        queue.put(1);
        queue.put(2);
        queue.put(3);
        queue.put(4);
        int ret=queue.take();
        System.out.println(ret);
        ret=queue.take();
        System.out.println(ret);
        ret=queue.take();
        System.out.println(ret);
        ret=queue.take();
        System.out.println(ret);*/
    }
}
